package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;
import android.widget.RadioGroup;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPublishCargoBinding;
import com.sgb.kjwl.model.entity.ChoiceOppositePersonEntity;
import com.sgb.kjwl.model.entity.map.CargoMapEntity;
import com.sgb.kjwl.model.entity.self.GoodsSelectEntity;
import com.sgb.kjwl.model.entity.self.TypeChooseEntity;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.InvoiceRateEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.Constants;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.PickerHelper;
import com.sgb.kjwl.utils.RangeFocusChangeListener;
import com.sgb.kjwl.view.constant.RequestCode;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.activity.WebActivity;
import com.sgb.kjwl.view.ui.adapter.CargoMoreAdapter;
import com.sgb.kjwl.view.ui.adapter.self.logistics.CargoPublishPersonAdapter;
import com.sgb.kjwl.view.widget.ClearEditText;
import com.sgb.kjwl.view.widget.OppositePersonPopWindow;
import com.sgb.kjwl.view.widget.StoragePopWindow;
import com.sgb.kjwl.view.widget.transport.GoodsTypeChooseDialog;
import com.sgb.kjwl.viewmodel.self.logistics.ReleaseCargoModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.util.ArrayUtil;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * Describe:发布普通货源
 * 2.1.8.6 紧急改版
 * Author:  yangLei
 * Date:    2021/12/3
 */
public class PublishCargoActivity extends AppActivity implements GoodsTypeChooseDialog.CallBack {
    ReleaseCargoModel viewModel;
    ActivityPublishCargoBinding binding;
    //选择器
    private OptionsPickerView<GoodsInfoTypeEntity3> mLoadModePicker;
    private TimePickerView mDatePicker;
    //发货地/收货地列表
    private int mLocationIndex;//选中地址下标
    private List<CargoPublishEntity.LocationEntity> mLocationList;
    private CargoPublishPersonAdapter mLocationAdapter;
    //付款约定信息列表
    private List<SingleItemEntity> mPayList;
    private CargoMoreAdapter mPayAdapter;
    //违约责任信息列表
    private List<SingleItemEntity> mContractList;
    private CargoMoreAdapter mContractAdapter;
    //数据实体类
    private CargoPublishEntity mEntity;
    //运费是否电议
    private boolean isBargaining = false;
    private Drawable imgBargain;

    private OptionsPickerView<GoodsInfoTypeEntity3> mModePicker;
    private OptionsPickerView<GoodsSelectEntity> mPackagePicker;
    private GoodsTypeChooseDialog goodsTypeDialog;
    private OptionsPickerView<TypeChooseEntity> pricingPicker;//定价方式选择器
    private final List<TypeChooseEntity> pricingBeans = new ArrayList<>();
    private OptionsPickerView<GoodsInfoTypeEntity3> mPayPicker;//付款方式选择器
    private OptionsPickerView<InvoiceRateEntity> mInvoicePicker;//发票
    private OppositePersonPopWindow<ChoiceOppositePersonEntity> oppositePersonPopWindow;

    private OptionsPickerView<GoodsInfoTypeEntity3> peoplePicker;
    private final List<GoodsInfoTypeEntity3> peopleBeans = new ArrayList<>();

    /**
     * 默认普通货源
     */
    public static void start(Context context) {
        start(context, true);
    }

    /**
     * 跳转发布货源
     *
     * @param isNormal true:普通货源 false:竞价货源
     */
    public static void start(Context context, boolean isNormal) {
        Intent intent;
        if (isNormal) {
            intent = new Intent(context, PublishCargoActivity.class);
        } else {
            intent = new Intent(context, RevisionReleaseBiddingCargoActivity.class);
        }
        intent.putExtra(RouterKey.BOOLEAN, isNormal);
        context.startActivity(intent);
    }

    /**
     * 跳转编辑货源
     *
     * @param no       货源no
     * @param isNormal true:普通货源 false:竞价货源
     */
    public static void start(Context context, String no, boolean isNormal) {
        Intent intent;
        if (isNormal) {
            intent = new Intent(context, PublishCargoActivity.class);
        } else {
            intent = new Intent(context, RevisionReleaseBiddingCargoActivity.class);
        }
        intent.putExtra(RouterKey.NO, no);
        context.startActivity(intent);
    }

    /**
     * 地图跳转发布普通货源
     *
     * @param entity 地图传值
     */
    public static void start(Context context, CargoMapEntity entity) {
        Intent intent;
        intent = new Intent(context, PublishCargoActivity.class);
        intent.putExtra(RouterKey.BOOLEAN, true);
        intent.putExtra(RouterKey.DATA, entity);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        viewModel = new ViewModelProvider(this).get(ReleaseCargoModel.class);
    }

    @Override
    protected void init() {
        binding = DataBindingUtil.setContentView(PublishCargoActivity.this, R.layout.activity_publish_cargo);
        binding.setLifecycleOwner(this);
        binding.tvReleaseCargoProtocol.setText(Html.fromHtml("发布货源即表示您同意"
                + "<font color='#5792FD'>《经营帮货物运输协议》</font>所有内容"));
        //初始化页面
        initPicker();
        initRecycler();
        initData();
        initEvent();
    }

    private void initPicker() {
        //报价截止时间选择器
        mDatePicker = PickerHelper.with(this).getCommonTimeBuild("选择报价截止时间", (date, v) -> {
            long time = DateUtils.getCustomizeDayNight(0, date.getTime()).getTime();
            if (mEntity.getEndTime() != 0 && time > mEntity.getEndTime()) {
                MToast.showToast(this, "报价截止时间不能大于装货结束时间");
                return;
            }
            //设置数据
            mEntity.setBiddingEndTime(time);
            binding.tvReleaseCargoQuotation.setText(DateUtils.stampToDay5(String.valueOf(time)));
        })
                .setType(new boolean[]{true, true, true, false, false, false})
                .build();

        pricingBeans.add(new TypeChooseEntity("0", "货车响应公式价格"));
        pricingBeans.add(new TypeChooseEntity("1", "货车竞价争取承运"));

        pricingPicker = PickerHelper.with(this).getCommonPicker("承运方式", pricingBeans, (options1, options2, options3, v) -> {
            if (pricingBeans.size() > options1) {
                binding.tvPricingType.setText(pricingBeans.get(options1).getName());
                mEntity.setPricingType(pricingBeans.get(options1).getName());
            }
        });

        peopleBeans.add(new GoodsInfoTypeEntity3(UserOperating.getInstance().getUserNo(), UserOperating.getInstance().getUserRealName()));
        peoplePicker = PickerHelper.with(this).getCommonPicker("咨询对接人", peopleBeans, (options1, options2, options3, v) -> {
            if (peopleBeans.size() > options1) {
                binding.tvConsultDockingPeople.setText(peopleBeans.get(options1).getName());
                mEntity.setContactPersonNo(peopleBeans.get(options1).getNo());
                mEntity.setContactPerson(peopleBeans.get(options1).getName());
            }
        });
    }

    /**
     * 设置付款方式
     */
    private void syncPayType(List<GoodsInfoTypeEntity3> list) {
        mPayPicker = PickerHelper.with(this).getCommonPicker("付款方式", list, (options1, options2, options3, v) -> {
            GoodsInfoTypeEntity3 entity = list.get(options1);
            if (entity != null && !TextUtils.isEmpty(entity.getName())) {
                mEntity.setPayType(entity.getName());
                handlerPayType(entity.getName());
            }
        });
    }

    /**
     * 处理结算方式字符串
     *
     * @param payType
     */
    private void handlerPayType(String payType) {
        if (TextUtils.isEmpty(payType))
            return;
        binding.tvReleaseCargoPayWay.setText(DefaultUtil.getString(payType));
        //选择分批支付，展示预付款、装车后支付、到货验收支付字段。非必填，0-100内，限数字输入，最大三位数。提交时校验，Toast提示“预付款不能大于100%”，“装车后支付不能大于100%”，“到货验收支付不能大于100%”。
        if (payType.equals("分批支付")) {
            binding.llAdvancePay.setVisibility(View.VISIBLE);
            binding.llLoadingPay.setVisibility(View.VISIBLE);
            binding.rlArrivalPay.setVisibility(View.VISIBLE);
        } else {
            binding.llAdvancePay.setVisibility(View.GONE);
            binding.llLoadingPay.setVisibility(View.GONE);
            binding.rlArrivalPay.setVisibility(View.GONE);
        }
    }

    /**
     * 设置发票要求
     */
    private void syncInvoice(List<InvoiceRateEntity> list) {
        if (list == null) return;
        mInvoicePicker = PickerHelper.with(this).getCommonPicker("发票要求", list, (options1, options2, options3, v) -> {
            InvoiceRateEntity entity = list.get(options1);
            //设置数据
            if (!TextUtils.isEmpty(entity.getRate()))
                mEntity.setTariff(Double.parseDouble(entity.getRate()));
            if (!TextUtils.isEmpty(entity.getNo()))
                mEntity.setInvoiceNo(entity.getNo());
            if (!TextUtils.isEmpty(entity.getInvoiceRequest()))
                mEntity.setInvoice(entity.getInvoiceRequest());
            //设置回显
            binding.tvReleaseCargoInvoice.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    private void initRecycler() {
        //发货人/收货人列表
        mLocationList = new ArrayList<>();
        mLocationAdapter = new CargoPublishPersonAdapter(mLocationList);
        binding.rvReleaseCargoPerson.setNestedScrollingEnabled(false);
        binding.rvReleaseCargoPerson.setLayoutManager(new LinearLayoutManager(this));
        mLocationAdapter.bindToRecyclerView(binding.rvReleaseCargoPerson);
        //付款约定列表
        mPayList = new ArrayList<>();
        mPayAdapter = new CargoMoreAdapter(mPayList);
        binding.rvReleaseCargoPayAgreement.setNestedScrollingEnabled(false);
        binding.rvReleaseCargoPayAgreement.setLayoutManager(new LinearLayoutManager(this));
        mPayAdapter.bindToRecyclerView(binding.rvReleaseCargoPayAgreement);
        //违约责任列表
        mContractList = new ArrayList<>();
        mContractAdapter = new CargoMoreAdapter(mContractList);
        binding.rvReleaseCargoContract.setNestedScrollingEnabled(false);
        binding.rvReleaseCargoContract.setLayoutManager(new LinearLayoutManager(this));
        mContractAdapter.bindToRecyclerView(binding.rvReleaseCargoContract);
    }

    private void initEvent() {
        binding.setOnClick(this);
        binding.includeTitle.ivBack.setOnClickListener(this);
        mLocationAdapter.setOnItemClickListener((adapter, view, position) -> {
            mLocationIndex = position;
            CargoPublishPersonActivity.start(PublishCargoActivity.this,
                    mLocationList.get(position), RequestCode.CODE_SEVEN);
        });
        //接口回调
        viewModel.ldPublish.observe(this, this::syncData);
        viewModel.ldHandleType.observe(this, this::initLoadPicker);
        viewModel.ldDistance.observe(this, entity -> {
            //设置总运程数据
            mEntity.setDistance(entity);
            if (entity == null || entity.getTotalDistance() == null) {
                binding.totalFortune.setVisibility(View.GONE);
            } else {
                binding.totalFortune.setVisibility(View.VISIBLE);
                binding.totalFortune.setText(String.format("总运程约 %skm", NumberUtil.trim0(entity.getTotalDistance() / 1000)));
            }
        });
        //跳转回调
        viewModel.ldJump.observe(this, integer -> {
            if (integer == 0) {
                //跳转费用信息
                CargoPublishCostActivity.start(this, mEntity, RequestCode.CODE_THREE);
            }
        });
        //定位回调
        viewModel.ldLocation.observe(this, aBoolean -> {
            mLocationAdapter.notifyDataSetChanged();
            //重算运程
            calculateLineDistance();
        });

        //****************************2.1.86
        viewModel.ldPrice.observe(this, aBoolean -> adjustTotalFreight());
        viewModel.ldMode.observe(this, this::syncGoodsMode);
        viewModel.ldPackage.observe(this, this::syncPackageMode);
        viewModel.ldPay.observe(this, this::syncPayType);
        viewModel.ldInvoiceRateEntity.observe(this, this::syncInvoice);
        viewModel.listdata.observe(this, data -> {
            List<ChoiceOppositePersonEntity> choiceOppositePersonEntityList = new ArrayList<>();
            if (mEntity != null && !TextUtils.isEmpty(mEntity.getContactPerson())) {
                for (ChoiceOppositePersonEntity personEntity : data) {
                    if (mEntity.getContactPersonNo().equals(personEntity.getUserNo()) && mEntity.getContactPerson().equals(personEntity.getname())) {
                        personEntity.setChoice(true);
                    }
                    choiceOppositePersonEntityList.add(personEntity);
                }
                if (oppositePersonPopWindow != null) {
                    oppositePersonPopWindow.setData(choiceOppositePersonEntityList);
                }
            } else {
                if (oppositePersonPopWindow != null) {
                    oppositePersonPopWindow.setData(data);
                }
            }

        });
        //重量
//        binding.etReleaseCargoWeight.setOnFocusChangeListener(new RangeFocusChangeListener(0.01, 999.99) {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                super.onFocusChange(v, hasFocus);
//                addEtPrefix(hasFocus, binding.etReleaseCargoWeight);
//                handlerWeightInput();
//            }
//        });
        binding.etReleaseCargoWeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                handlerWeightInput();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //体积
//        binding.etReleaseCargoVolume.setOnFocusChangeListener(new RangeFocusChangeListener(0.01, 999.99) {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                super.onFocusChange(v, hasFocus);
//                addEtPrefix(hasFocus, binding.etReleaseCargoVolume);
//                handlerVolumeInput();
//            }
//        });
        binding.etReleaseCargoVolume.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                handlerVolumeInput();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //信息费
        binding.noMsgPrice.setChecked(true);
        binding.msgPriceGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.no_msg_price:
                        binding.rlEt.setVisibility(View.GONE);
                        binding.etReleaseCargoMsgPrice.setText("");
                        mEntity.setChooseMessagePrice(1);
                        break;
                    case R.id.have_msg_price:
                        binding.rlEt.setVisibility(View.VISIBLE);
                        mEntity.setChooseMessagePrice(0);
                        break;
                }
            }
        });
        //货源类型
        binding.rgPattern.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.general_cargo:
                        if (mEntity != null)
                            mEntity.setPattern(0);
                        break;
                    case R.id.bidding_cargo:
                        if (mEntity != null)
                            mEntity.setPattern(1);
                        break;
                }
            }
        });

        binding.etReleaseCargoMsgPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String msgPrice = binding.etReleaseCargoMsgPrice.getText().toString();
                //设置信息费
                if (TextUtils.isEmpty(msgPrice)) {
                    mEntity.setMsgPrice(null);
                } else {
                    mEntity.setMsgPrice(NumberUtil.convertToDouble(msgPrice));
                }
                adjustMsgPrice();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //运费
        binding.etReleaseCargoFreight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String freight = binding.etReleaseCargoFreight.getText().toString();
                //设置运费
                if (TextUtils.isEmpty(freight)) {
                    mEntity.setFreight(0);
                } else {
                    mEntity.setFreight(NumberUtil.convertToDouble(freight));
                }
                viewModel.ldPrice.postValue(true);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //预付款比例
        binding.tvAdvancePay.setOnFocusChangeListener(new RangeFocusChangeListener(0, 100) {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                super.onFocusChange(v, hasFocus);
                String text = binding.tvAdvancePay.getText().toString();
                //设置运费
                if (TextUtils.isEmpty(text)) {
                    mEntity.setPrepaidProportion(null);
                } else {
                    mEntity.setPrepaidProportion(NumberUtil.convertToInt(text));
                }
            }
        });
        //装车后支付
        binding.tvLoadingPay.setOnFocusChangeListener(new RangeFocusChangeListener(1, 100) {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                super.onFocusChange(v, hasFocus);
                String text = binding.tvLoadingPay.getText().toString();
                //设置运费
                if (TextUtils.isEmpty(text)) {
                    mEntity.setPaymentAfterLoading(null);
                } else {
                    mEntity.setPaymentAfterLoading(NumberUtil.convertToInt(text));
                }
            }
        });
        //到货验收支付
        binding.tvArrivalPay.setOnFocusChangeListener(new RangeFocusChangeListener(1, 100) {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                super.onFocusChange(v, hasFocus);
                String text = binding.tvArrivalPay.getText().toString();
                //设置运费
                if (TextUtils.isEmpty(text)) {
                    mEntity.setArrivalAcceptancePayment(null);
                } else {
                    mEntity.setArrivalAcceptancePayment(NumberUtil.convertToInt(text));
                }
            }
        });
    }

    private void handlerWeightInput() {
        String weight = binding.etReleaseCargoWeight.getText().toString();
        //设置货重
        if (!TextUtils.isEmpty(weight)) {
            weight = weight.startsWith("约") ? weight.substring(1) : weight;
            mEntity.setGoodsWeight(NumberUtil.convertToDouble(weight));
        } else {
            mEntity.setGoodsWeight(0);
        }
        viewModel.ldPrice.postValue(true);
    }

    private void handlerVolumeInput() {
        String volume = binding.etReleaseCargoVolume.getText().toString();
        //设置体积
        if (!TextUtils.isEmpty(volume)) {
            volume = volume.startsWith("约") ? volume.substring(1) : volume;
            mEntity.setGoodsVolume(NumberUtil.convertToDouble(volume));
        } else {
            mEntity.setGoodsVolume(0);
        }
        viewModel.ldPrice.postValue(true);
    }

    private void initData() {
        boolean isNormal = getIntent().getBooleanExtra(RouterKey.BOOLEAN, true);
        CargoMapEntity mapData = getIntent().getParcelableExtra(RouterKey.DATA);
        String no = getIntent().getStringExtra(RouterKey.NO);

        //运费单位默认选中“趟”
        binding.tvReleaseCargoOnce.setSelected(true);

        //地图传值
        if (mapData != null) {
            viewModel.assemblyMapData(mapData, isNormal);
        } else if (TextUtils.isEmpty(no)) {
            mEntity = new CargoPublishEntity();
            mEntity.setFreightMode(1);
            mEntity.setPattern(isNormal ? 0 : 1);
            binding.rgPattern.check(isNormal ? R.id.general_cargo : R.id.bidding_cargo);
            initCommon();
        } else {
            viewModel.getDetail(this, no);
        }

        //获取页面所需数据
        viewModel.getHandleType();
        viewModel.getGoodsMode(this);
        viewModel.getPackageMode(this);
        viewModel.getPayType();
        viewModel.getInvoices(this);
    }

    /**
     * 设置货物类型数据
     */
    private void syncGoodsMode(List<GoodsInfoTypeEntity3> list) {
        mModePicker = PickerHelper.with(this).getCommonPicker("选择货物类型", list, (options1, options2, options3, v) -> {
            GoodsInfoTypeEntity3 entity = list.get(options1);
            //设置数据
            mEntity.setGoodsModeNo(entity.getNo());
            mEntity.setGoodsModeName(entity.getName());
            //设置回显
            binding.tvReleaseCargoType.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    /**
     * 设置包装方式数据
     */
    private void syncPackageMode(List<GoodsSelectEntity> list) {
        mPackagePicker = PickerHelper.with(this).getCommonPicker("选择包装方式", list, (options1, options2, options3, v) -> {
            GoodsSelectEntity entity = list.get(options1);
            //设置数据
            mEntity.setPackageModeNo(entity.getNo());
            mEntity.setPackageModeName(entity.getName());
            //设置回显
            binding.tvReleaseCargoPackage.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    /**
     * 初始化装卸方式弹窗
     */
    private void initLoadPicker(List<GoodsInfoTypeEntity3> list) {
        //装卸方式选择器
        mLoadModePicker = PickerHelper.with(this).getCommonPicker("选择装卸方式", list, (options1, options2, options3, v) -> {
            GoodsInfoTypeEntity3 entity = list.get(options1);
            mEntity.setLoadModeNo(entity.getNo());
            mEntity.setLoadMode(entity.getName());
            binding.tvReleaseCargoLoadMode.setText(entity.getName());
            //设置列表数据
            viewModel.getLocationListByLoadMode(mLocationList, entity.getNo());
            mLocationAdapter.notifyDataSetChanged();
            //重算运程
            calculateLineDistance();
        });
    }

    /**
     * 编辑货源时同步货源数据使用
     */
    private void syncData(CargoPublishEntity entity) {
        if (entity == null) {
            boolean isNormal = getIntent().getBooleanExtra(RouterKey.BOOLEAN, true);
            mEntity = new CargoPublishEntity();
            mEntity.setFreightMode(1);
            mEntity.setPattern(isNormal ? 0 : 1);
            binding.rgPattern.check(isNormal ? R.id.general_cargo : R.id.bidding_cargo);
            initCommon();
            return;
        }
        binding.rgPattern.check(entity.getPattern() == 1 ? R.id.bidding_cargo : R.id.general_cargo);
        mEntity = entity;
        initCommon();
        //同步数据
        syncCar(mEntity);
        //判断是否是地图进入,地图进入只用设置车辆信息
        if (entity.isFromMap()) {
            entity.setFromMap(false);
        } else {
            syncDate(mEntity);
            syncGoods(mEntity);
            syncCost(mEntity);
            syncMoreData(mEntity);
            syncContact(mEntity);
        }
        //设置竞价结束时间
        if (mEntity.getPattern() == 1 && mEntity.getBiddingEndTime() != 0) {
            binding.tvReleaseCargoQuotation.setText(DateUtils.stampToDay5(String.valueOf(mEntity.getBiddingEndTime())));
        }
    }

    /**
     * 设置通用数据
     */
    private void initCommon() {
        //设置标题
        binding.includeTitle.titleView.setText(mEntity.getPattern() == 0 ? "发布货运项目" : "发布货运项目");
        binding.llReleaseCargoQuotation.setVisibility(mEntity.getPattern() == 0 ? View.GONE : View.VISIBLE);
        //设置默认数据
        if (TextUtils.isEmpty(mEntity.getCompanyNo())) {
            //设置用户信息
            mEntity.setCompanyNo(UserOperating.getInstance().getTeamOrCompanyNameNo());
            mEntity.setCompany(UserOperating.getInstance().getTeamOrCompanyName());
            mEntity.setContact(UserOperating.getInstance().getUserRealName());
            mEntity.setContactTel(UserOperating.getInstance().getPhone());
        }
        List<CargoPublishEntity.ContactInfoEntity> contactInfo = new ArrayList<>();
        CargoPublishEntity.ContactInfoEntity contact = new CargoPublishEntity.ContactInfoEntity();
        contact.setContrcts(TextUtils.isEmpty(mEntity.getConnection()) ? UserOperating.getInstance().getUserRealName() : mEntity.getConnection());
        contact.setContrctsNumber(TextUtils.isEmpty(mEntity.getConnectionPhone()) ? UserOperating.getInstance().getPhone() : mEntity.getConnectionPhone());
        contactInfo.add(contact);
        mEntity.setContactInfo(contactInfo);
        if (ArrayUtil.isNotNullAndEmpty(mEntity.getContactInfo())) {
            binding.tvPublishCargoContact.setText(String.format("%s/%s",
                    mEntity.getContactInfo().get(0).getContrcts(),
                    mEntity.getContactInfo().get(0).getContrctsNumber()));
        }
        //设置装卸方式
        initDefaultLoadMode();
    }

    /**
     * 初始化默认装卸方式
     */
    private void initDefaultLoadMode() {
        //只有初始发布填写定位数据，历史货源/编辑货源数据不填写
        if (!TextUtils.isEmpty(mEntity.getLoadModeNo())) {
            //编辑货源/历史货源
            binding.tvReleaseCargoLoadMode.setText(mEntity.getLoadMode());
            viewModel.getLocationListByLoadMode(mLocationList, mEntity.getLoadModeNo());
            mLocationAdapter.notifyDataSetChanged();
            //重算运程
            calculateLineDistance();
        } else {
            mEntity.setLoadModeNo("11");
            mEntity.setLoadMode("一装一卸");
            binding.tvReleaseCargoLoadMode.setText(mEntity.getLoadMode());
            viewModel.getLocationListByLoadMode(mLocationList, mEntity.getLoadModeNo());
            viewModel.getCurrentLocation(this);
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_release_cargo_history:
                //选择历史货源
                CargoPublishHistoryActivity.start(this, mEntity.getPattern(), RequestCode.CODE_ZERO);
                break;
            case R.id.ll_release_cargo_load_mode:
                //选择装卸方式
                mLoadModePicker.show();
                break;
            case R.id.ll_release_cargo_load_date:
                //选择装货时间
//                if (mEntity.getPattern() == 1) {
//                    CargoPublishDateActivity.start(this, mEntity, RequestCode.CODE_ONE);
//                } else {
                OrdinaryCargoPublishDateActivity.start(this, mEntity, RequestCode.CODE_ONE);
//                }
                break;
//            case R.id.ll_release_cargo_cargo_info:
//                //选择货物信息
//                CargoPublishCargoInfoActivity.start(this, mEntity, RequestCode.CODE_TWO);
//                break;
//            case R.id.ll_release_cargo_price:
//                //选择费用要求
//                if (mEntity.getPattern() == 1) {
//                    CargoPublishCostActivity.start(this, mEntity, RequestCode.CODE_THREE);
//                } else {
//                    OrdinaryCargoPublishCostActivity.start(this, mEntity, RequestCode.CODE_THREE);
//                }
//                break;
            case R.id.ll_release_cargo_car_info:
                //选择车辆信息
                if (TextUtils.isEmpty(mEntity.getGoodsModeNo())) {
                    MToast.showToast(this, "请先选择货物类型");
//                } else if (mEntity.getPattern() == 1) {
//                    CargoPublishCarInfoActivity.start(this, mEntity, RequestCode.CODE_FOUR);
                } else {
                    OrdinaryCargoPublishCarInfoActivity.start(this, mEntity, RequestCode.CODE_FOUR);
                }
                break;
            case R.id.ll_release_cargo_quotation:
                //选择报价截止时间
                mDatePicker.show();
                break;
            case R.id.ll_release_cargo_more:
                //选择更多信息
                CargoPublishMoreActivity.start(this, mEntity, RequestCode.CODE_FIVE);
                break;
            case R.id.tv_release_cargo_submit:
                //提交货源
                clearAllFocus();
                if (mEntity.getMsgPrice() != null && mEntity.getMsgPrice() > 0) {//信息费不为0，企业/个人(团队)，未开通资金中心，提示需要先去开通
                    if (UserOperating.getInstance().isNotOpenFundAccount(this, PermissionCheckUtil.KEY_HUOYUANGUANLI)) {
                        return;
                    }
                }
                if (!binding.etReleaseCargoWeight.getText().toString().isEmpty()) {
                    if (mEntity.getGoodsWeight() < 0.01 || mEntity.getGoodsWeight() > 999.99) {
                        MToast.showToast(this, "请输入0.01-999.99内的货重");
                        return;
                    }
                }
                if (!binding.etReleaseCargoVolume.getText().toString().isEmpty()) {
                    if (mEntity.getGoodsVolume() < 0.01 || mEntity.getGoodsVolume() > 999.99) {
                        MToast.showToast(this, "请输入0.01-999.99内的体积");
                        return;
                    }
                }
                if (binding.cbReleaseCargoProtocol.isChecked()) {
                    mEntity.setLocationList(mLocationList);
                    viewModel.releaseCargo(this, binding.tvReleaseCargoSubmit, mEntity);
                } else {
                    MToast.showToast(this, "请先勾选同意经营帮货物运输协议");
                }
                break;
            case R.id.tv_release_cargo_protocol:
                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.TRANSPORT_URL));
                WebActivity.start(PublishCargoActivity.this);
                break;


            //**************2.1.86
            case R.id.ll_release_cargo_type:
                if (goodsTypeDialog == null) {
                    goodsTypeDialog = GoodsTypeChooseDialog.newInstance((ArrayList<GoodsInfoTypeEntity3>) viewModel.ldMode.getValue()).callBack(this);
                }
                goodsTypeDialog.show(getSupportFragmentManager(), "top");
                break;
            case R.id.ll_release_cargo_package:
                if (mPackagePicker != null) {
                    mPackagePicker.show();
                }
                break;

            case R.id.tv_release_cargo_once:
                if (binding.tvReleaseCargoOnce.isSelected()) {
                    return;
                }
                switchFreightMode(0);
                break;

            case R.id.tv_release_cargo_weight:
                if (binding.tvReleaseCargoWeight.isSelected()) {
                    return;
                }
                //判断是否填写货重
                if (mEntity.getGoodsWeight() == 0) {
                    MToast.showToast(this, "请先填写货重");
                    return;
                }
                switchFreightMode(1);
                break;

            case R.id.tv_release_cargo_volume:
                if (binding.tvReleaseCargoVolume.isSelected()) {
                    return;
                }
                //判断是否填写体积
                if (mEntity.getGoodsVolume() == 0) {
                    MToast.showToast(this, "请先填写货物体积");
                    return;
                }
                switchFreightMode(2);
                break;

            case R.id.ll_pricing_type:
                if (pricingPicker != null) {
                    pricingPicker.show();
                }
                break;

            case R.id.ll_release_cargo_pay_way:
                if (mPayPicker != null) {
                    mPayPicker.show();
                }
                break;

            case R.id.ll_release_cargo_invoice:
                if (mInvoicePicker != null) {
                    mInvoicePicker.show();
                }
                break;

            case R.id.rl_temp_goods_choose:
                mEntity.setGoodsPattern("1");
                handlerSendGoodsPattern(1);
                break;

            case R.id.rl_long_time_goods_choose:
                mEntity.setGoodsPattern("2");
                handlerSendGoodsPattern(2);
                break;

            case R.id.ll_consult_docking_people:
                if (UserOperating.getInstance().isCompany()) {
                    showConsultingPeoplePopWindow();
                } else {
                    if (peoplePicker != null)
                        peoplePicker.show();
                }
                break;

            case R.id.btn_bargaining:
                handlerBargainStyle(true);
                break;
            case R.id.ll_publish_cargo_contact:
                //联系信息
                CargoPublishContactActivity.start(this, mEntity, RequestCode.CODE_SIX);
                break;
        }
    }

    /**
     * 是否电议处理
     *
     * @param isSwitch 是否是点击按钮切换运费类型
     */
    private void handlerBargainStyle(boolean isSwitch) {
        if (mEntity == null)
            return;
        if (isSwitch) {
            if (isBargaining) {
                isBargaining = false;
                mEntity.setFreightType(0);
                hideCostInfo(false);
                adjustTotalFreight();//切换后需要重新计算运费合计并显示
            } else {
                isBargaining = true;
                mEntity.setFreightType(1);
                hideCostInfo(true);
                binding.tvReleaseCargoFreight.setText("电议");
                binding.tvFreightCalculationMethod.setText("运费合计计算 ：货物单价 × 数量");
            }
        } else {
            if (mEntity.getFreightType() == 1) {//电议
                isBargaining = true;
                hideCostInfo(true);
            } else {//一口价
                isBargaining = false;
                hideCostInfo(false);
            }
        }
    }

    private void hideCostInfo(boolean isHide) {
        if (isHide) {
            imgBargain = getResources().getDrawable(R.mipmap.icon_checkbox_pressed_large);
            binding.llFreightUnit.setVisibility(View.GONE);
            binding.llFreightUnitPrice.setVisibility(View.GONE);
            binding.llPricingType.setVisibility(View.GONE);
        } else {
            imgBargain = getResources().getDrawable(R.mipmap.icon_checkbox_no_pressed_large);
            binding.llFreightUnit.setVisibility(View.VISIBLE);
            binding.llFreightUnitPrice.setVisibility(View.VISIBLE);
            binding.llPricingType.setVisibility(View.VISIBLE);
        }
        imgBargain.setBounds(0, 0, imgBargain.getMinimumWidth(), imgBargain.getMinimumHeight());
        binding.btnBargaining.setCompoundDrawables(imgBargain, null, null, null);
    }

    /**
     * 发货模式显示处理
     *
     * @param type
     */
    private void handlerSendGoodsPattern(int type) {
        if (type == 2) {
            binding.checkTempIv.setImageResource(R.mipmap.icon_item_unchecked_white);
            binding.checkLongTimeIv.setImageResource(R.mipmap.icon_item_checked_blue);
        } else {
            binding.checkTempIv.setImageResource(R.mipmap.icon_item_checked_blue);
            binding.checkLongTimeIv.setImageResource(R.mipmap.icon_item_unchecked_white);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        //历史货源回调
        if (requestCode == RequestCode.CODE_ZERO && data != null) {
            String no = data.getStringExtra(RouterKey.NO);
            viewModel.getDetail(this, no, true);
            return;
        }
        //发货人/收货人回调
        if (requestCode == RequestCode.CODE_SEVEN) {
            syncLocation(data);
            //计算运程
            calculateLineDistance();
            return;
        }
        //货源子页面数据
        if (data == null) return;
        CargoPublishEntity entity = data.getParcelableExtra(RouterKey.DATA);
        if (entity == null) return;
        switch (requestCode) {
            case RequestCode.CODE_ONE:
                syncDate(entity);
                break;
            case RequestCode.CODE_TWO:
                syncGoods(entity);
                break;
//            case RequestCode.CODE_THREE:
//                syncCost(entity);
//                break;
            case RequestCode.CODE_FOUR:
                syncCar(entity);
                break;
            case RequestCode.CODE_FIVE:
                syncMoreData(entity);
                break;
            case RequestCode.CODE_SIX:
                if (ArrayUtil.isNotNullAndEmpty(entity.getContactInfo())) {
                    entity.setConnection(entity.getContactInfo().get(0).getContrcts());
                    entity.setConnectionPhone(entity.getContactInfo().get(0).getContrctsNumber());
                }
                syncContact(entity);
                break;
        }
    }

    /**
     * 同步装货时间
     */
    private void syncDate(CargoPublishEntity entity) {
        mEntity = entity;
        if (mEntity.getBeginTime() == 0) {
            binding.tvReleaseCargoLoadDate.setText("");
            return;
        }
//        if (mEntity.getPattern() == 1) {
//            binding.tvReleaseCargoLoadDate.setText(String.format("%s—%s",
//                    DateUtils.stampToDay5(String.valueOf(mEntity.getBeginTime())),
//                    DateUtils.stampToDay5(String.valueOf(mEntity.getEndTime()))));
//        } else {
        //设置普通货源装货时间
        binding.tvReleaseCargoLoadDate.setText(CargoConstant.stampFormatListLoadTime(
                mEntity.getBeginTime(), mEntity.getStartPointTime(),
                mEntity.getEndTime(), mEntity.getEndPointTime()));
//        }
    }

    /**
     * 设置货源信息
     */
    private void syncGoods(CargoPublishEntity entity) {
        //判断货物类型是否改变，改变了清空车辆信息
        if (entity.getCarTypeList() == null || entity.getCarLenList() == null) {
            syncCar(entity);
        }
        mEntity = entity;
        if (!TextUtils.isEmpty(mEntity.getGoodsModeName())) {
            binding.tvReleaseCargoType.setText(mEntity.getGoodsModeName());
        }
        if (!TextUtils.isEmpty(mEntity.getPackageModeName())) {
            binding.tvReleaseCargoPackage.setText(mEntity.getPackageModeName());
        }
        if (mEntity.getGoodsWeight() != 0) {
            binding.etReleaseCargoWeight.setText(String.format("约%s", NumberUtil.trim0(mEntity.getGoodsWeight())));
        }
        if (mEntity.getGoodsVolume() != 0) {
            binding.etReleaseCargoVolume.setText(String.format("约%s", NumberUtil.trim0(mEntity.getGoodsVolume())));
        }
        //1表示未选择  0表示选择
        if (mEntity.getChooseMessagePrice() != 0) {
            binding.noMsgPrice.setChecked(true);
        } else {
            binding.haveMsgPrice.setChecked(true);
            if (mEntity.getMsgPrice() != null) {
                binding.etReleaseCargoMsgPrice.setText(NumberUtil.trim0(mEntity.getMsgPrice()));
            }
        }
        if (mEntity.getFreight() != 0) {
            binding.etReleaseCargoFreight.setText(NumberUtil.trim0(mEntity.getFreight()));
        }

        if (!TextUtils.isEmpty(mEntity.getPricingType())) {
            binding.tvPricingType.setText(mEntity.getPricingType());
        }
        if (!TextUtils.isEmpty(mEntity.getPayType())) {
            handlerPayType(mEntity.getPayType());
        }

        if (mEntity.getPrepaidProportion() != null) {
            binding.tvAdvancePay.setText(mEntity.getPrepaidProportion() + "");
        }
        if (mEntity.getPaymentAfterLoading() != null) {
            binding.tvLoadingPay.setText(mEntity.getPaymentAfterLoading() + "");
        }
        if (mEntity.getArrivalAcceptancePayment() != null) {
            binding.tvArrivalPay.setText(mEntity.getArrivalAcceptancePayment() + "");
        }

        if (mEntity.isInvoiceChanges()) {
            mEntity.setInvoiceNo("");
            mEntity.setInvoice("");
            mEntity.setTariff(null);
        } else if (!TextUtils.isEmpty(mEntity.getInvoice()) && mEntity.getTariff() != null && !TextUtils.isEmpty(mEntity.getInvoiceNo())) {
            if (mEntity.getInvoice().equals("不开发票")) {
                binding.tvReleaseCargoInvoice.setText(mEntity.getInvoice());
            } else {
                String invoiceStr = NumberUtil.trim0(mEntity.getTariff()) + "%" + mEntity.getInvoice();
                binding.tvReleaseCargoInvoice.setText(invoiceStr);
            }
        }

        if (!TextUtils.isEmpty(mEntity.getGoodsPattern()) && mEntity.getGoodsPattern().equals(2)) {
            handlerSendGoodsPattern(2);
        } else {
            handlerSendGoodsPattern(1);
        }

        if (!TextUtils.isEmpty(mEntity.getContactPerson())) {
            binding.tvConsultDockingPeople.setText(mEntity.getContactPerson());
        }

        handlerBargainStyle(false);//处理是否电议UI逻辑

        switch (mEntity.getFreightMode()) {
            case CargoPublishEntity.FreightMode.MODE_WEIGHT://吨
                switchFreightMode(1);
                break;
            case CargoPublishEntity.FreightMode.MODE_VOLUME://方
                switchFreightMode(2);
                break;
            case CargoPublishEntity.FreightMode.MODE_ONCE://趟
            default://默认趟
                switchFreightMode(0);
                break;
        }
        //计算总运费
        adjustTotalFreight();
    }

    /**
     * 同步费用要求
     */
    private void syncCost(CargoPublishEntity entity) {
        mEntity = entity;
        adjustMsgPrice();
        adjustTotalFreight();
    }

    /**
     * 修改信息费
     */
    private void adjustMsgPrice() {
        if (mEntity.getMsgPrice() == null) {
            binding.tvReleaseCargoMsgPrice.setText(R.string.default_release_cargo_price);
        } else {
            binding.tvReleaseCargoMsgPrice.setText(String.format("%s元", NumberUtil.trim0(mEntity.getMsgPrice())));
        }
    }

    /**
     * 同步车辆信息
     */
    private void syncCar(CargoPublishEntity entity) {
        mEntity = entity;
        if (mEntity.getCarTypeList() == null || mEntity.getCarLenList() == null) {
            binding.tvReleaseCargoCarInfo.setText("");
            return;
        }
        StringBuilder builder = new StringBuilder();
        //设置普通货源用车类型
//        if (mEntity.getPattern() == 0) {
//            builder.append("/").append(entity.getUseCarType() == 1 ? "整车" : "零担");
//        }
        if (mEntity.getCarTypeList() != null && mEntity.getCarLenList() != null) {
            for (GoodsInfoTypeEntity3 type : mEntity.getCarTypeList()) {
                if (mEntity.getCarTypeList().indexOf(type) == 0) {
                    builder.append(" ");
                } else {
                    builder.append("/");
                }
                builder.append(type.getName());
            }
            for (GoodsInfoTypeEntity3 type : mEntity.getCarLenList()) {
                if (mEntity.getCarLenList().indexOf(type) == 0) {
                    builder.append(" ");
                } else {
                    builder.append("/");
                }
                builder.append(type.getName());
            }
        }
        if (mEntity.getHeightHurdle() != 0) {
            builder.append(" 栏高").append(NumberUtil.trim0(mEntity.getHeightHurdle())).append("米");
        }
        if (mEntity.getIsDump() != null) {
            builder.append(" ").append(mEntity.getIsDump() == 1 ? "自卸" : "非自卸");
        }
        if (!TextUtils.isEmpty(builder.toString())) {
            binding.tvReleaseCargoCarInfo.setText(builder.substring(1));
        }
    }

    /**
     * 同步联系人信息
     */
    private void syncContact(CargoPublishEntity entity) {
        mEntity = entity;
        //提交数据时检查是否填写联系人
        if (ArrayUtil.isNotNullAndEmpty(entity.getContactInfo())) {
            binding.tvPublishCargoContact.setText(String.format("%s/%s%s",
                    entity.getContactInfo().get(0).getContrcts(),
                    entity.getContactInfo().get(0).getContrctsNumber(),
                    entity.getContactInfo().size() == 1 ? "" : "等"));
        } else {
            binding.tvPublishCargoContact.setText("");
        }
    }

    /**
     * 同步更多数据
     */
    private void syncMoreData(CargoPublishEntity entity) {
        mEntity = entity;
        //违约责任
        syncContract(entity);
        //付款约定
        syncPayAgreement(entity);
        //整体判断内容    2.1.86 统一隐藏处理
        if (ArrayUtil.isNullOrEmpty(mPayList) && ArrayUtil.isNullOrEmpty(mContractList)) {
            binding.tvReleaseCargoMore.setHint(R.string.release_cargo_more_hint);
            binding.tvReleaseCargoMore.setText("");
//            binding.lineReleaseCargoContractBottom.setVisibility(View.GONE);
        } else {
            binding.tvReleaseCargoMore.setText("已填写");
//            binding.lineReleaseCargoContractBottom.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 同步付款约定
     */
    private void syncPayAgreement(CargoPublishEntity entity) {
        mEntity = entity;
        mPayList.clear();
        if (entity.getArrivalTime() != null && entity.getArrivalTime() != 0) {
            mPayList.add(new SingleItemEntity("到货时间", String.format("开始运输后%s天内", NumberUtil.trim0(mEntity.getArrivalTime()))));
        }
        if (mEntity.getPerformanceBond() != null && mEntity.getPerformanceBond() != 0) {
            mPayList.add(new SingleItemEntity("履约保证金", String.format("%s元", NumberUtil.trim0(mEntity.getPerformanceBond()))));
        }
        //装车要求
        if (mEntity.getRequire() != 0) {
            mPayList.add(new SingleItemEntity("装车要求", CargoConstant.getLoadRequire(mEntity.getRequire())));
        }
//        if (!TextUtils.isEmpty(entity.getPayType())) {
//            mPayList.add(new SingleItemEntity("付款方式", DefaultUtil.getString(entity.getPayType())));
//        }
        if (!TextUtils.isEmpty(entity.getReceiptAccountRequire())) {
            mPayList.add(new SingleItemEntity("收款账户要求", DefaultUtil.getString(entity.getReceiptAccountRequire())));
        }
        if (!TextUtils.isEmpty(entity.getOtherPaymentRequire())) {
            mPayList.add(new SingleItemEntity("付款要求", DefaultUtil.getString(entity.getOtherPaymentRequire())));
        }
        //发票要求信息匹配检测
//        if (mEntity.isInvoiceChanges()) {
//            mEntity.setInvoiceNo("");
//            mEntity.setInvoice("");
//            mEntity.setTariff(null);
//            showFieldAlterDialog();
//        } else if (!TextUtils.isEmpty(mEntity.getInvoice()) && mEntity.getTariff() != null && !TextUtils.isEmpty(mEntity.getInvoiceNo())) {
//            if (mEntity.getInvoice().equals("不开发票")) {
//                mPayList.add(new SingleItemEntity("发票要求", entity.getInvoice()));
//            } else {
//                String invoiceStr = NumberUtil.trim0(mEntity.getTariff()) + "%" + mEntity.getInvoice();
//                mPayList.add(new SingleItemEntity("发票要求", invoiceStr));
//            }
//        }
//        if (!TextUtils.isEmpty(mEntity.getInvoicingCompanyName())) {
//            mPayList.add(new SingleItemEntity("开票信息", String.format("%s/%s",
//                    mEntity.getInvoicingCompanyName(),
//                    mEntity.getInvoicingTaxNumber())));
//        }
        mPayAdapter.notifyDataSetChanged();
        //判断付款信息是否为空    2.1.86 统一隐藏处理
//        if (ArrayUtil.isNullOrEmpty(mPayList)) {
//            binding.rvReleaseCargoPayAgreement.setVisibility(View.GONE);
//        } else {
//            binding.rvReleaseCargoPayAgreement.setVisibility(View.VISIBLE);
//        }

        if (!TextUtils.isEmpty(entity.getShipperOwnerUnit())) {
            mPayList.add(new SingleItemEntity("货主单位", DefaultUtil.getString(entity.getShipperOwnerUnit())));
        }
        if (!TextUtils.isEmpty(entity.getShipperContact())) {
            mPayList.add(new SingleItemEntity("货主联系人", DefaultUtil.getString(entity.getShipperContact())));
        }
        if (!TextUtils.isEmpty(entity.getShipperPhone())) {
            mPayList.add(new SingleItemEntity("货主联系电话", DefaultUtil.getString(entity.getShipperPhone())));
        }
    }

    /**
     * 因 2.0.4 发票要求字段调整，提示用户重新选择
     */
    private void showFieldAlterDialog() {
        new RoundDialog.Builder(this)
                .title("提示")
                .content("平台发票要求已调整，使用历史货源发布需重新选择该信息")
                .confirm("我知道了")
                .singleBtn(true)
                .confirmCallback(v -> {
                    if (mEntity != null) {
                        mEntity.setInvoiceChanges(false);
                    }
                })
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .show();
    }

    /**
     * 同步违约责任
     */
    private void syncContract(CargoPublishEntity entity) {
        mEntity = entity;
        mContractList.clear();
        if (!TextUtils.isEmpty(entity.getLostPromise())) {
            mContractList.add(new SingleItemEntity("货物损坏或丢失赔偿约定", DefaultUtil.getString(entity.getLostPromise())));
        }
        if (!TextUtils.isEmpty(entity.getOverduePromise())) {
            mContractList.add(new SingleItemEntity("逾期装货或送货责任约定", DefaultUtil.getString(entity.getOverduePromise())));
        }
        if (!TextUtils.isEmpty(entity.getOtherPromise())) {
            mContractList.add(new SingleItemEntity("其他约定", DefaultUtil.getString(entity.getOtherPromise())));
        }
        //自定义字段
        if (mEntity.getCustomList() != null && !mEntity.getCustomList().isEmpty()) {
            mContractList.addAll(mEntity.getCustomList());
        }
        mContractAdapter.notifyDataSetChanged();
        //判断数据是否为空  2.1.86 统一隐藏处理
//        if (ArrayUtil.isNullOrEmpty(mContractList)) {
//            binding.rvReleaseCargoContract.setVisibility(View.GONE);
//        } else {
//            binding.rvReleaseCargoContract.setVisibility(View.VISIBLE);
//        }
    }

    /**
     * 同步收货/发货
     */
    private void syncLocation(Intent data) {
        if (data == null) return;
        CargoPublishEntity.LocationEntity locationEntity = data.getParcelableExtra(RouterKey.DATA);
        if (locationEntity == null) return;
        mLocationList.set(mLocationIndex, locationEntity);
        mLocationAdapter.notifyDataSetChanged();
        //重设缓存数据
        viewModel.setCacheLocation(locationEntity.getCacheIndex(), locationEntity);
    }

    /**
     * 计算运程
     */
    private void calculateLineDistance() {
        viewModel.calculateLineDistance(mLocationList, mEntity.getLoadModeNo());
    }

    /**
     * 调整运费--更改了货物信息和运费信息之后计算
     */
    private void adjustTotalFreight() {
        //设置普通货源运费展示
        if (mEntity.getFreightType() == 1) {//电议
            mEntity.setTotalFreight(0);
            binding.tvReleaseCargoFreight.setText("电议");
            binding.tvFreightCalculationMethod.setText("运费合计计算 ：货物单价 × 数量");
            return;
        }

        if (mEntity.getFreight() == 0) {//运费为0的情况
            mEntity.setTotalFreight(0);
            binding.tvReleaseCargoFreight.setText(R.string.default_release_cargo_price);
            binding.tvFreightCalculationMethod.setText("运费合计计算 ：货物单价 × 数量");
            return;
        }

        //根据运费类型计算运费
        double total;
        switch (mEntity.getFreightMode()) {
            case CargoPublishEntity.FreightMode.MODE_ONCE:
                total = mEntity.getFreight();
                mEntity.setTotalFreight(total);
                binding.tvReleaseCargoFreight.setText(String.format("%s元", NumberUtil.trim0(total)));
                binding.tvFreightCalculationMethod.setText("运费合计计算 ：" + mEntity.getFreight() + "元/趟 x 1");
                break;
            case CargoPublishEntity.FreightMode.MODE_WEIGHT:
                if (mEntity.getGoodsWeight() == 0) {
                    total = 0;
                    binding.tvReleaseCargoFreight.setText(R.string.default_release_cargo_price);
                } else {
                    total = mEntity.getGoodsWeight() * mEntity.getFreight();
                    binding.tvReleaseCargoFreight.setText(String.format("%s元", NumberUtil.trim0(total)));
                }
                mEntity.setTotalFreight(total);
                binding.tvFreightCalculationMethod.setText("运费合计计算 ：" + mEntity.getFreight() + "元/吨 x " + NumberUtil.trim0(mEntity.getGoodsWeight()));
                break;
            case CargoPublishEntity.FreightMode.MODE_VOLUME:
                if (mEntity.getGoodsVolume() == 0) {
                    total = 0;
                    binding.tvReleaseCargoFreight.setText(R.string.default_release_cargo_price);
                } else {
                    total = mEntity.getGoodsVolume() * mEntity.getFreight();
                    binding.tvReleaseCargoFreight.setText(String.format("%s元", NumberUtil.trim0(total)));
                }
                mEntity.setTotalFreight(total);
                binding.tvFreightCalculationMethod.setText("运费合计计算 ：" + mEntity.getFreight() + "元/方 x " + NumberUtil.trim0(mEntity.getGoodsVolume()));
                break;
        }
    }

    /**
     * 添加前缀
     */
    private void addEtPrefix(boolean hasFocus, ClearEditText editText) {
        Editable editable = editText.getText();
        //有焦点时移除前缀
        if (hasFocus) {
            if (editable != null && editable.toString().startsWith("约")) {
                editText.setText(editable.toString().substring(1));
            }
            return;
        }
        //失去焦点时添加前缀
        if (editable != null && editable.length() > 0 && !editable.toString().startsWith("约")) {
            editText.setText(String.format("约%s", editable));
        }
    }

    @Override
    public void select(GoodsInfoTypeEntity3 entity) {
        if (entity == null) return;
        //设置数据
        if (TextUtils.isEmpty(entity.getParentNo())) {
            mEntity.setGoodsModeNo(entity.getNo());
            mEntity.setGoodsModeName(entity.getName());
        } else {
            mEntity.setGoodsModeNo(entity.getParentNo());
            mEntity.setGoodsModeName(entity.getName());
            mEntity.setSecondGoodsTypeNo(entity.getNo());
        }
        String name = entity.getName();
        if (name.contains("/")) {
            name = name.substring(name.indexOf("/") + 1);
        }
        //设置回显
        binding.tvReleaseCargoType.setText(DefaultUtil.getString(name));
    }

    /**
     * 切换运费方式
     */
    private void switchFreightMode(int position) {
        int count = binding.llReleaseCargoFreightType.getChildCount();
        for (int i = 0; i < count; i++) {
            binding.llReleaseCargoFreightType.getChildAt(i).setSelected(false);
        }
        binding.llReleaseCargoFreightType.getChildAt(position).setSelected(true);
        //设置运费方式
        switch (position) {
            case 0:
                mEntity.setFreightMode(CargoPublishEntity.FreightMode.MODE_ONCE);
                binding.tvReleaseCargoFreightSuffix.setText("元/趟");
                break;
            case 1:
                mEntity.setFreightMode(CargoPublishEntity.FreightMode.MODE_WEIGHT);
                binding.tvReleaseCargoFreightSuffix.setText("元/吨");
                break;
            case 2:
                mEntity.setFreightMode(CargoPublishEntity.FreightMode.MODE_VOLUME);
                binding.tvReleaseCargoFreightSuffix.setText("元/方");
                break;
        }

        //重新同步费用信息
        syncCost(mEntity);
    }


    /**
     * 咨询对接人弹窗
     */
    public void showConsultingPeoplePopWindow() {
        if (oppositePersonPopWindow == null) {
            oppositePersonPopWindow = new OppositePersonPopWindow(this);
            oppositePersonPopWindow.setBgView(binding.grayLayout);
            oppositePersonPopWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            oppositePersonPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            oppositePersonPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
                @Override
                public void result(Object key1, Object key2, Object key3) {
                    ChoiceOppositePersonEntity storageManEntity = (ChoiceOppositePersonEntity) key1;//选择返回数据
                    if (storageManEntity == null) {
                        binding.tvConsultDockingPeople.setText("");
                        mEntity.setContactPerson("");
                        mEntity.setContactPersonNo("");
                        oppositePersonPopWindow.dismiss();
                    } else {
                        binding.tvConsultDockingPeople.setText(storageManEntity.getname());
                        mEntity.setContactPerson(storageManEntity.getname());
                        mEntity.setContactPersonNo(storageManEntity.getUserNo());
                        oppositePersonPopWindow.dismiss();
                    }

                }
            });
            oppositePersonPopWindow.inputTextInterface(new StoragePopWindow.InputTextInterface() {
                @Override
                public void input(String s) {
                    hideInput();
                    viewModel.getPoppositePerSonList(s);
                }
            });

            oppositePersonPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
                @Override
                public void disMiss() {

                }
            });
        }
        viewModel.getPoppositePerSonList("");
        if (!oppositePersonPopWindow.isShowing()) {
            oppositePersonPopWindow.showDownPopwindow(binding.llConsultDockingPeople, true);
        }
    }

    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
}
